<?php
/**
 * 会员管理
 */
namespace app\admin\controller;

use think\facade\Request;

class User extends MyController
{
    /**
     * 会员管理页面
     */
    public function index()
    {
        $current = input('page',1);
        $length=10;
        $start = ($current-1)*$length;

        $user = db('user')
            ->order('u_id','DESC')
            ->limit($start,$length)
            ->paginate($length);
        $this->assign([
            'user'=>$user,
        ]);
        return view();
    }

    /**
     * 管理员页面
     */
    public function admin()
    {
        $current = input('page',1);
        $limit = 5;
        $start = ($current-1) * $limit;
        $admin = db('admin_user')
            ->alias('a')
            ->leftJoin('role r','a.r_id=r.r_id')
            ->limit($start,$limit)
            ->paginate($limit);

        //角色
        $role = db('role')->select();

        $this->assign([
            'admin' => $admin,
            'role' => $role,
        ]);
        return view();
    }

    /**
     * ajax请求 添加管理员   修改管理员
     */
    public function adminEdit()
    {
        if (Request::isAjax())
        {
            $data = Request::post();
            if (empty($data['ad_id'])){
                //添加管理员
                $insertdata['username'] = $data['username'];
                $insertdata['verify'] = md5(rand(10000,99999));
                $insertdata['add_time'] = time();
                $insertdata['r_id'] = $data['r_id'];
                $insertdata['password'] = md5(md5($data['password']).$insertdata['verify']);
                $res = db('admin_user')
                        ->data($insertdata)
                        ->insert();
                if ($res){echo 1;exit;}else{echo 0;exit;}
            }else{
                //修改管理员
                $adid = $data['ad_id'];
                $updatedata['username'] = $data['username'];
                $updatedata['r_id'] = $data['r_id'];
                if (empty($data['password'])){
                    if(db('admin_user')->where('ad_id',$adid)->update($updatedata))
                    {
                        echo 1;exit;
                    }else{
                        echo 0;exit;
                    }
                }else{
                    $updatedata['verify'] = md5(rand(10000,99999));
                    $updatedata['password'] = md5(md5($data['password']).$updatedata['verify']);
                    if(db('admin_user')->where('ad_id',$adid)->update($updatedata))
                    {
                        echo 1;exit;
                    }else{
                        echo 0;exit;
                    }
                }
            }
        }
    }
    /**
     * 角色管理界面
     */
    public function role(){
        $role = db('role')->select();
        $this->assign([
            'role'=> $role,
        ]);
        return view();
    }
}
